package com.foreknow.elm.framework;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.处理字符编码
        //设置从服务器端向客户端返回的内容类型     MIME类型： text/html
        response.setContentType("application/json;charset=utf-8");
//        客户端向服务器端请求的编码格式（否则会产生乱码），   默认：IOS  8859-1
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        response.setCharacterEncoding("UTF-8");
//        2.获取到客户端发送的请求路径（url部分路径）
        String url = request.getServletPath();
        //3.根据获取到的路径获取到对应的类名和方法名
        String className = url.substring(1, url.lastIndexOf("/"));
        String methodName = url.substring(url.lastIndexOf("/") + 1);
        try {
            //4.通过Class.forName（）获取到Controller中类的信息
            Class clazz = Class.forName("com.foreknow.elm.controller." + className);
            //将获取的类转换为对象
            Object con = clazz.newInstance();
            //5.获取到方法
            Method method = clazz.getMethod(methodName, new Class[]{HttpServletRequest.class});
            //6.调用方法
            Object result = method.invoke(con, new Object[]{request});
            //7.将结果result以JSON形式响应给客户端浏览器
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(result);
            out.print(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
